import { useState, useEffect } from 'react';
import { Layout, Menu, Upload, message, Card, Row, Col, Modal, Radio, Space, Button, Checkbox, Tabs, Spin } from 'antd';
import { PictureOutlined, UploadOutlined, DeleteOutlined, AppstoreOutlined, UnorderedListOutlined, VideoCameraOutlined } from '@ant-design/icons';
import { S3Client, PutObjectCommand, DeleteObjectCommand, ListObjectsCommand } from '@aws-sdk/client-s3';
import { s3Config } from './config/s3Config';
import './App.css';
import VideoManager from './components/VideoManager';

const { Header, Content } = Layout;

const s3Client = new S3Client(s3Config);

// 生成缩略图URL
const getThumbnailUrl = (url: string) => {
  // 调整为竖屏9:16比例，宽度200，高度自动计算
  return `${url}?x-oss-process=image/resize,w_200,h_356,m_fill`;
};

function App() {
  const [images, setImages] = useState<Array<{ key: string; url: string; thumbnailUrl: string; folder?: string; type: string; size?: number }>>([]);
  const [currentFolder, setCurrentFolder] = useState<string>('/');
  const [folders, setFolders] = useState<string[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [selectedImages, setSelectedImages] = useState<string[]>([]);
  const [isSelectionMode, setIsSelectionMode] = useState(false);
  const [activeTab, setActiveTab] = useState('images');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchImages();
  }, [currentFolder]);

  const fetchImages = async () => {
    setLoading(true);
    try {
      const response = await s3Client.send(new ListObjectsCommand({
        Bucket: s3Config.bucket
      }));
      
      if (response.Contents) {
        const allItems = response.Contents.map(item => {
          const key = item.Key || '';
          const parts = key.split('/');
          const folder = parts.length > 1 ? parts.slice(0, -1).join('/') + '/' : '/';
          const url = `${s3Config.endpoint}/${s3Config.bucket}/${key}`;
          return {
            key,
            url,
            thumbnailUrl: getThumbnailUrl(url),
            folder,
            type: key.toLowerCase().endsWith('.mp4') ? 'video' : 'image',
            size: item.Size
          };
        });

        // 提取所有文件夹
        const uniqueFolders = Array.from(new Set(allItems.map(item => item.folder)));
        setFolders(uniqueFolders);

        // 过滤当前文件夹的图片（只显示图片文件）
        const filteredImages = allItems.filter(item => 
          item.folder === currentFolder && 
          item.type === 'image' &&
          (item.key.toLowerCase().endsWith('.jpg') || 
           item.key.toLowerCase().endsWith('.jpeg') || 
           item.key.toLowerCase().endsWith('.png') || 
           item.key.toLowerCase().endsWith('.gif') || 
           item.key.toLowerCase().endsWith('.webp'))
        );
        setImages(filteredImages);
      }
    } catch (error) {
      message.error('获取图片列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleUpload = async (file: File) => {
    // 检查文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      message.error('只支持上传图片文件（JPG、PNG、GIF、WebP）');
      return false;
    }

    try {
      console.log('开始上传文件:', { fileName: file.name, fileSize: file.size, fileType: file.type });
      const key = currentFolder === '/' ? file.name : `${currentFolder}${file.name}`;
      console.log('生成的文件Key:', key);
      
      // 直接使用ArrayBuffer作为请求体
      const buffer = await file.arrayBuffer();
      
      const command = new PutObjectCommand({
        Bucket: s3Config.bucket,
        Key: key,
        Body: buffer,
        ContentType: file.type
      });
      console.log('准备发送S3命令:', { bucket: s3Config.bucket, key });

      await s3Client.send(command);
      console.log('S3上传成功');
      message.success('上传成功');
      fetchImages();
      return false;
    } catch (error) {
      console.error('上传失败:', error);
      message.error('上传失败');
      return false;
    }
  };

  const handleDelete = async (key: string) => {
    try {
      const command = new DeleteObjectCommand({
        Bucket: s3Config.bucket,
        Key: key
      });

      await s3Client.send(command);
      message.success('删除成功');
      fetchImages();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handlePreview = (url: string) => {
    setPreviewImage(url);
    setPreviewVisible(true);
  };

  const handleBatchDelete = async () => {
    try {
      await Promise.all(
        selectedImages.map(key =>
          s3Client.send(
            new DeleteObjectCommand({
              Bucket: s3Config.bucket,
              Key: key
            })
          )
        )
      );
      message.success('批量删除成功');
      setSelectedImages([]);
      setIsSelectionMode(false);
      fetchImages();
    } catch (error) {
      message.error('批量删除失败');
    }
  };

  const toggleImageSelection = (key: string) => {
    setSelectedImages(prev =>
      prev.includes(key)
        ? prev.filter(k => k !== key)
        : [...prev, key]
    );
  };

  const handleSelectAll = () => {
    if (selectedImages.length === images.length) {
      setSelectedImages([]);
    } else {
      setSelectedImages(images.map(img => img.key));
    }
  };

  return (
    <Layout className="layout">
      <Header className="header">
        <div className="logo">
          <PictureOutlined /> 媒体管理系统
        </div>
        <Menu 
          theme="dark" 
          mode="horizontal" 
          defaultSelectedKeys={['1']} 
          items={[{ key: '1', label: '媒体库' }]}
          style={{ flex: 1 }}
        />
      </Header>
      <Content className="content">
        <div className="content-wrapper">
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={[
              {
                key: 'images',
                label: (
                  <span>
                    <PictureOutlined />
                    图片管理
                  </span>
                ),
                children: (
                  <>
                    <div style={{ marginBottom: '20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px' }}>
                      <Space wrap>
                        <span>当前位置：</span>
                        {folders.map(folder => (
                          <Radio.Button
                            key={folder}
                            value={folder}
                            onClick={() => setCurrentFolder(folder)}
                            style={{ 
                              backgroundColor: currentFolder === folder ? '#1890ff' : 'white',
                              color: currentFolder === folder ? 'white' : 'rgba(0, 0, 0, 0.85)'
                            }}
                          >
                            {folder === '/' ? '根目录' : folder.replace('/', '')}
                          </Radio.Button>
                        ))}
                      </Space>
                      <Space wrap>
                        <Button
                          type={isSelectionMode ? 'primary' : 'default'}
                          onClick={() => {
                            setIsSelectionMode(!isSelectionMode);
                            setSelectedImages([]);
                          }}
                        >
                          {isSelectionMode ? '退出多选' : '多选模式'}
                        </Button>
                        {isSelectionMode && (
                          <>
                            <Button onClick={handleSelectAll}>
                              {selectedImages.length === images.length ? '取消全选' : '全选'}
                            </Button>
                            <Button
                              type="primary"
                              danger
                              disabled={selectedImages.length === 0}
                              onClick={handleBatchDelete}
                            >
                              批量删除 ({selectedImages.length})
                            </Button>
                          </>
                        )}
                      </Space>
                    </div>

                    <Upload
                      beforeUpload={handleUpload}
                      showUploadList={false}
                      accept="image/jpeg,image/png,image/gif,image/webp"
                    >
                      <div className="upload-area">
                        <UploadOutlined style={{ fontSize: '24px', marginBottom: '8px' }} />
                        <div>点击或拖拽图片上传（支持 JPG、PNG、GIF、WebP）</div>
                      </div>
                    </Upload>

                    <Space style={{ marginBottom: '20px' }}>
                      <Radio.Group value={viewMode} onChange={e => setViewMode(e.target.value)}>
                        <Radio.Button value="grid"><AppstoreOutlined /> 网格视图</Radio.Button>
                        <Radio.Button value="list"><UnorderedListOutlined /> 列表视图</Radio.Button>
                      </Radio.Group>
                    </Space>

                    <Spin spinning={loading}>
                      {viewMode === 'grid' ? (
                        <Row gutter={[16, 16]} className="image-grid">
                          {images.map(image => (
                            <Col key={image.key} xs={24} sm={12} md={8} lg={6}>
                              <Card
                                hoverable
                                className="image-card"
                                cover={
                                  <div style={{ position: 'relative' }}>
                                    <img
                                      alt={image.key}
                                      src={image.thumbnailUrl}
                                      className="image-preview"
                                      loading="lazy"
                                      onError={(e) => {
                                        const target = e.target as HTMLImageElement;
                                        target.src = '';
                                      }}
                                    />
                                    {isSelectionMode && (
                                      <Checkbox
                                        checked={selectedImages.includes(image.key)}
                                        onChange={() => toggleImageSelection(image.key)}
                                        style={{ position: 'absolute', top: 8, right: 8, zIndex: 1 }}
                                      />
                                    )}
                                  </div>
                                }
                                actions={[
                                  <DeleteOutlined key="delete" onClick={() => handleDelete(image.key)} />,
                                  <PictureOutlined key="preview" onClick={() => handlePreview(image.url)} />
                                ]}
                              >
                                <Card.Meta
                                  title={image.key.split('/').pop()}
                                  description={`大小: ${(image.size || 0).toLocaleString()} bytes`}
                                />
                              </Card>
                            </Col>
                          ))}
                        </Row>
                      ) : (
                        <div className="list-view">
                          {images.map(image => (
                            <div key={image.key} className="list-item">
                              <img
                                src={image.thumbnailUrl}
                                alt={image.key}
                                className="list-item-image"
                                loading="lazy"
                                onError={(e) => {
                                  const target = e.target as HTMLImageElement;
                                  target.src = '';
                                }}
                              />
                              <div className="list-item-info">
                                <div>{image.key.split('/').pop()}</div>
                                <div>大小: {(image.size || 0).toLocaleString()} bytes</div>
                              </div>
                              <div className="list-item-actions">
                                {isSelectionMode && (
                                  <Checkbox
                                    checked={selectedImages.includes(image.key)}
                                    onChange={() => toggleImageSelection(image.key)}
                                  />
                                )}
                                <Space>
                                  <Button type="text" icon={<PictureOutlined />} onClick={() => handlePreview(image.url)}>
                                    预览
                                  </Button>
                                  <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleDelete(image.key)}>
                                    删除
                                  </Button>
                                </Space>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </Spin>
                  </>
                )
              },
              {
                key: 'videos',
                label: (
                  <span>
                    <VideoCameraOutlined />
                    视频管理
                  </span>
                ),
                children: <VideoManager />
              }
            ]}
          />
        </div>

        <Modal
          open={previewVisible}
          footer={null}
          onCancel={() => setPreviewVisible(false)}
          width={800}
          style={{ top: 20 }}
        >
          <img alt="preview" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Content>
    </Layout>
  );
}

export default App;
